#coding:utf-8

import getpass
import os

from prettytable import PrettyTable
import xml.etree.cElementTree as ET

versionAll = ['#']                                                # 全局版本数组

def handleXML(root):


    dic = {}                                                          # 全局字典，储存整理好后的所有数据
    code = 0                                                          # 用来处理版本数据
    num = 0                                                           # 全局号码变量，确定唯一设备

    # 迭代所有版本
    for version in root[0][1]:

        # 去除无效数据，将所有版本号添加进数组
        if len(version.text.split('.')) > 1:
            versionAll.append(version.text.split('.').pop())

        i = 0
        temp = []

        # 迭代所有版本中的设备
        for device in list(version):
            num = num + 1
            i = i + 1
            if i % 2 == 0:
                temp.append(device.text)
                currentVer = versionAll[(code + 1) / 2]
                tempDic = {num/2:{currentVer:temp}}
                dic.update(tempDic)
                temp = []
            else:
                temp.append(device.text.split('.').pop())


        code = code + 1

    return dic


def drawTable(dic):

    devices = []                                          # 全部的设备名称
    lastVer = ''
    row = []
    rows = []

    table = PrettyTable(versionAll)

    # 获取全部的设备名称
    for info in dic:
        for ver in dic[info]:
            devices.append(dic[info][ver][0])

    # 对数据进行去重处理
    devices = sorted(set(devices),key=devices.index)

    for device in devices:
        isFirstCol = True
        for info in dic:
            for ver in dic[info]:
                if isFirstCol:
                    if dic[info][ver][0] == device:
                        row.append(dic[info][ver][0])
                        row.append(info)
                        isFirstCol = False
                else:
                    if dic[info][ver][0] == device:
                        row.append(info)
        rowLen = len(row)
        for i in range(0,len(versionAll) - rowLen):
            row.append('-')
        table.add_row(row)


        rows.append(row)
        # 重置新的一行
        row = []

    return table



if __name__ == '__main__':

    rootAddr = "/Users/" + getpass.getuser() + "/Library/Developer/CoreSimulator/Devices/"   # 模拟器根目录

    devicesListFile = rootAddr + "device_set.plist"                  # 模拟器描述文件

    deviceList = ET.ElementTree(file=devicesListFile)                 # 用ElementTree解析模拟器描述文件（XML）

    root = deviceList.getroot()                                       # 根节点

    allInfo = handleXML(root)                                         # 解析出来的所有信息
    table = drawTable(allInfo)                                        # 根据解析出的信息画图表

    print table

    while True:
        try:
            answer = input('请输入表格中相应的数字，即可打开对应目录：')
            for x in allInfo[answer]:
                addr = allInfo[answer][x][1]

            print '当前打开的是：' + str(allInfo[answer])
            os.system('open ' + rootAddr + addr)

        except Exception as e:
            print e
            print ('请输入正确的编号！!')
